<?php
// +----------------------------------------------------------------------
// | 用户模块
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\Area as AreaModel;
use think\facade\Db;
/**
 * 地区控制器
 * @package app\si\admin
 */
class Area extends Admin
{
    /**
     * 地区列表
     */
    public function index($pid = 0, $keyword = '')
    {
        // 查询
        $map = $this->getMap();
		if ($keyword == '') $map[] = ['pid', '=', $pid];
		$title = AreaModel::getFullName($pid);
        // 数据列表
        $data_list = AreaModel::where($map)->select();
		
		if ($pid == 0) {
			$btnQuery = [
				'class' => 'btn btn-primary ajax-get confirm',
				'icon'  => 'fa fa-fw fa-refresh',
				'title' => '更新数据',
				'href'  => url('query'),
				'data-title' => '真的要更新吗？'
			];
		} else {
			$btnQuery = [
				'class' => 'btn btn-primary hidden',
				'icon'  => 'fa fa-fw fa-refresh',
				'title' => '更新数据',
			];
		}
		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setSearch(['name' => '区域名称', 'id' => '区域ID']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
               ['id', 'ID'],
			   ['pid', '上级ID'],
               ['name', '区域', 'link' , url('index', ['pid' => '__id__']), '', 'pop'],
			   ['status', '状态', 'switch'],
               ['sort', '排序', 'text.edit'],
               ['right_button', '操作', 'btn']
            ])
			->setPageTitle($title)
			// ->addTopButton('custom', $btnAdd) // 新增按钮
            ->addTopButtons('enable,disable') // 批量添加顶部按钮
			->addTopButton('custom', $btnQuery) // 更新按钮
            ->addRightButton('edit') // 添加右侧按钮
            // ->addRightButton('delete', ['data-tips' => '删除社保后，将不可恢复！']) // 添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
			->setTableName('si_list')
            ->fetch(); // 渲染模板
    }

    /**
     * 新增地区
     * @param int $pid 父级id
     */
    public function add($pid = 0)
    {
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Area');
            if(true !== $result) $this->error($result);
			$count = AreaModel::where('pid', $data['pid'])->count('id');
			$data['id'] = $data['pid'] . 100 + $count + 1;
            if ($area = AreaModel::create($data)) {
                cache('area_column', null);
                // 记录行为
                action_log('area_add', 'user_area', $area['id'], UID, $data['fullname']);
                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        }
		$pid_list = AreaModel::where('pid', app_config('si', 'area'))->column('fullname', 'id');
        // 显示添加页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['text:8', 'fullname', '村（社区）名称', '<span class="text-danger">必填</span>'],
				['select:8', 'pid', '乡镇（街道）', '', $pid_list, $pid],
				['radio', 'status', '立即启用', '', ['否', '是'], 1],
                ['text:8', 'sort', '排序', '', 100],
            ])
            ->fetch();
    }

    /**
     * 编辑地区
     */
    public function edit($id = '')
    {
        if ($id === 0) $this->error('参数错误');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Area');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            if (AreaModel::update($data)) {
                // 记录行为
                action_log('area_edit', 'user_area', $id, UID, $data['name']);
				cache('area_column', null);
				cache('area_info_'. $id, null);
                return $this->success('编辑成功', 'index');
            } else {
                return $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = AreaModel::where('id', $id)->find();
		// $pid_list = AreaModel::where('pid', app_config('si', 'area'))->column('fullname', 'id');
        // 显示编辑页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden', 'id'],
				['hidden', 'pid'],
                ['text:8', 'name', '地区名称', '<span class="text-danger">必填</span>'],
                // ['select:8', 'pid', '乡镇（街道）', '', $pid_list],
                ['radio', 'status', '立即启用', '', ['否', '是']],
                ['text:8', 'sort', '排序', ''],
            ])
            ->setFormData($info)
            ->fetch();
    }
	/**
	 * 更新基础数据
	 */
	public function query($pid = 0)
	{
		$api = config('map.get_mastArea');
		
		$return = json_decode(get_curls($api), true); // 请求接口
		if (!empty($return['result'][0])) {
			$data_list = $return['result'];
			$area = new AreaModel;
			$save_list = [];
			foreach($data_list[0] as $k => $v) {
				// 一级地区数据
				$save_list[] = [
					'id'	=> $v['id'],
					'pid'	=> 0,
					'name'	=> $v['fullname'],
					'lat' 	=> $v['location']['lat'],
					'lng' 	=> $v['location']['lng'],
				];
				// 二级数据
				if (!empty($v['cidx'])) {
					foreach($data_list[1] as $key => $value) {
						if ($key >= $v['cidx'][0] && $key <= $v['cidx'][1]) {
							$save_list[] = [
								'id'	=> $value['id'],
								'pid'	=> $v['id'],
								'name'	=> $value['fullname'],
								'lat' 	=> $value['location']['lat'],
								'lng' 	=> $value['location']['lng'],
							];
							// 三级数据
							if (!empty($value['cidx'])) {
								foreach($data_list[2] as $ke => $val) {
									if ($ke >= $value['cidx'][0] && $ke <= $value['cidx'][1]) {
										if (empty($val['name'])) $val['name'] = $val['fullname'];
										$save_list[] = [
											'id'	=> $val['id'],
											'pid'	=> $value['id'],
											'name'	=> $val['fullname'],
											'lat' 	=> $val['location']['lat'],
											'lng' 	=> $val['location']['lng'],
										];
									}
								}
							}
						}
					}
				}
			}
			if ($save_list) {
				// return $area->saveAll($save_list);
				Db::name('user_area')->insertAll($save_list);
				$this->success('更新成功');
			} else {
				$this->error('更新失败');
			}
		} else {
			$this->error($return['message']);
		}
	}
    /**
     * 删除地区
     * @param null $ids 地区id
     */
    public function delete($ids = null)
    {
        if ($ids === null) $this->error('参数错误');
		
		// 清除缓存
		cache('area_column', null);
		
        // 删除并记录日志
        $column_name = AreaModel::where('id', 'in', $ids)->column('title');
		
        return parent::delete(['area_delete', 'user_area', 0, UID, $column_name]);
    }

    /**
     * 启用地区
     * @param array $record 行为日志
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用地区
     * @param array $record 行为日志
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置地区状态：删除、禁用、启用
     * @param string $type 地区：enable/disable
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids           = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
		// 清除缓存
		cache('area_column', null);
		
        $column_delete = is_array($ids) ? '' : $ids;
        $column_names  = AreaModel::where('id', 'in', $ids)->column('title');
        return parent::setStatus($type, ['area_'.$type, 'user_area', $column_delete, UID, implode('、', $column_names)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');
        $column  = AreaModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $column . ')，新值：(' . $value . ')';
        return parent::quickEdit(['area_edit', 'user_area', $id, UID, $details]);
    }
}